<?php

namespace app\admin\controller\platform;

use app\admin\model\Admin;
use app\common\controller\Backend;
use ba\Tree;
use think\facade\Cache;
use Throwable;

/**
 * 地区管理
 */
class Area extends Backend
{

    protected array $noNeedPermission = ['*'];
    /**
     * Area模型对象
     * @var object
     * @phpstan-var \app\admin\model\Area
     */
    protected object $model;

    public function initialize (): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\Area;
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */


    /**
     * 查看
     * @throws Throwable
     */
    public function index (): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }
        $tree_area = Cache::instance()->get('tree_area');
        if (empty($tree_area)) {
            list($where, $alias, $limit, $order) = $this->queryBuilder();
            $res = $this->model
                ->field($this->indexField)
                ->withJoin($this->withJoinTable, $this->withJoinType)
                ->alias($alias)
                ->where($where)
                ->order($order)
                ->select()->toArray();
            $tree_area = Tree::instance()->assembleChild($res);
            Cache::instance()->set('tree_area', $tree_area);
        }
        $this->success('', [
            'list' => $tree_area,
        ]);
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index_city (): void
    {

        $res = $this->model
            ->where('level', 'in', "1,2")
            ->select()->toArray();
        foreach ($res as $key => $item) {
            $res[$key]['value'] = $item['id'];
            $res[$key]['label'] = $item['name'];
        }
        $tree_area = Tree::instance()->assembleChild($res);

        $this->success('', [
            'list' => $tree_area,
        ]);
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function city (): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        $city_ids = \app\admin\model\platform\OpenArea::column('city_id') ?? [];
        $quickSearch = $this->request->param('quickSearch');

        $tree_area_city = $this->model
            ->field('id,name')
            ->where('level', '=', 2)
            ->whereNotIn('id', $city_ids)
            ->where('name', 'like', "%{$quickSearch}%")
            ->order('id', 'asc')
            ->select()->toArray();
        $this->success('', [
            'list' => $tree_area_city,
        ]);
    }


}